﻿namespace JxcLite.Services;

class BillService(Context context) : ServiceBase(context), IBillService
{
    public Task<PagingResult<JxBillHead>> QueryBillsAsync(PagingCriteria criteria)
    {
        return Database.QueryPageAsync<JxBillHead>(criteria);
    }

    public async Task<JxBillHead> GetDefaultBillAsync(string type)
    {
        return new JxBillHead
        {
            Type = type,
            BillNo = await Database.GetMaxBillNoAsync(type),
            Status = FlowStatus.Save,
            BillDate = DateTime.Now
        };
    }

    public Task<List<JxBillList>> GetBillListsAsync(string headId)
    {
        return Database.QueryListAsync<JxBillList>(d => d.HeadId == headId);
    }

    public async Task<Result> DeleteBillsAsync(List<JxBillHead> models)
    {
        if (models == null || models.Count == 0)
            return Result.Error(Language.SelectOneAtLeast);

        var oldFiles = new List<string>();
        var result = await Database.TransactionAsync(Language.Delete, async db =>
        {
            foreach (var item in models)
            {
                await db.DeleteFilesAsync(item.Id, oldFiles);
                await db.DeleteAsync<JxBillList>(d => d.HeadId == item.Id);
                await db.DeleteAsync(item);
            }
        });
        if (result.IsValid)
            AttachFile.DeleteFiles(oldFiles);
        return result;
    }

    public async Task<Result> SaveBillAsync(UploadInfo<JxBillHead> info)
    {
        var model = info.Model;
        var vr = model.Validate(Context);
        if (!vr.IsValid)
            return vr;

        var user = CurrentUser;
        var bizType = "BillFiles";
        var bizFiles = info.Files.GetAttachFiles(user, nameof(JxBillHead.Files), bizType);
        return await Database.TransactionAsync(Language.Save, async db =>
        {
            if (model.IsNew)
                model.BillNo = await db.GetMaxBillNoAsync(model.Type);
            await db.AddFilesAsync(bizFiles, model.Id, bizType);
            model.Files = $"{model.Id}_{bizType}";
            await db.SaveAsync(model);
            //更新表体数据
            await db.DeleteAsync<JxBillList>(d => d.HeadId == model.Id);
            if (model.Lists != null && model.Lists.Count > 0)
            {
                foreach (var list in model.Lists)
                {
                    await db.InsertAsync(list, false);
                }
            }
        }, model);
    }
}